package com.hotel.controller;

import com.hotel.common.AjaxResult;
import com.hotel.domain.service.UserService;
import com.hotel.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

@RequestMapping("/user")
@Controller
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 登录
     * @param user 用户对象
     * @param session 会话对象
     * @return AjaxResult
     */
    @PostMapping("/login")
    @ResponseBody
    public AjaxResult login(@RequestBody User user, HttpSession session){
        User queryUser = userService.login(user);
        AjaxResult ajaxResult = new AjaxResult();
        if(queryUser == null){
            ajaxResult.setCode(AjaxResult.ERROR);
            ajaxResult.setMsg("用户名或密码错误");
        }else if(queryUser.getUserStatus() != 0){
            ajaxResult.setCode(AjaxResult.ERROR);
            ajaxResult.setMsg("请联系管理员更新用户状态");
        }else {
            ajaxResult.setCode(AjaxResult.SUCCESS);
            ajaxResult.setMsg("登录成功");
            //设置session
            session.setAttribute("user_session", queryUser);
        }
        return ajaxResult;
    }

    /**
     * 退出登录
     * @param session 会话对象
     * @return AjaxResult
     */
    @PostMapping("/logout")
    @ResponseBody
    public AjaxResult logout(HttpSession session){
        //删除session
        session.invalidate();
        return AjaxResult.queryAjax(null);
    }

    /**
     * 修改密码
     * @param users 用户对象数组
     * @return AjaxResult
     */
    @PostMapping("/changePassword")
    @ResponseBody
    public AjaxResult changePassword(@RequestBody User[] users){
        //查看旧密码是否正确
        if(userService.login(users[0]) == null){
            return new AjaxResult(AjaxResult.ERROR, "密码错误或该用户不是不是正常使用状态", null);
        }else {
            //如果正确则修改
            return AjaxResult.updateAjax(userService.changePassword(users[1]));
        }
    }

    /**
     * 获取当前登录用户
     * @param session 会话对象
     * @return AjaxResult
     */
    @GetMapping("/getUser")
    @ResponseBody
    public AjaxResult getUser(HttpSession session){
        return AjaxResult.queryAjax(session.getAttribute("user_session"));
    }

}
